//
//  DetailViewController.m
//  Porthole
//
//  Created by Dennis Chau on 12/8/11.
//  Copyright (c) 2011 Univeristy of Illinois at Chicago. All rights reserved.
//

#import "DetailViewController.h"

@interface DetailViewController ()
@property (strong, nonatomic) UIPopoverController *masterPopoverController;
- (void)configureView;
@end

@implementation DetailViewController
@synthesize pageController, pageContent;

@synthesize tcpConnection;
@synthesize connectServer;
@synthesize FIA;

@synthesize detailItem = _detailItem;
@synthesize detailDescriptionLabel = _detailDescriptionLabel;
@synthesize masterPopoverController = _masterPopoverController;

#
#
#pragma mark Handle Notification
#
#
- (void) setupRedrawFIA:(NSNotification *) notification
{
    if ([[notification name] isEqualToString:@"DetailVCRedrawFIA"])
    {
        if( self.tcpConnection.myState >= CLIENT_CONNECTED )
        {
            //NSLog(@"\t\tDetailVC :: Dumping img data to FIA and telling it to draw ");
            if( self.tcpConnection.byteData != nil )
            {            
                //Convert byte Array to NSData
                NSData *imgDataRecv = [ NSData dataWithBytes:self.tcpConnection.byteData length:self.tcpConnection.byteLen ];    
                //Convert NSData to UIImage
                UIImage *imgRecv = [UIImage imageWithData:imgDataRecv];
                
                FIA.overlayImg = imgRecv;
                FIA.overLayImgNew = YES;
                [FIA setNeedsDisplay];
            }
            
        }
    }
    
}

#
#
#pragma mark - FIA Delegates
#
#
- (void) connect:(FreeInteractionAreaView *)requestor
{
    if (requestor == self.FIA) 
    {
        [self.tcpConnection estConnectionToServer];
    }    
}


- (stateIAV) getConnectionState:(FreeInteractionAreaView *)requestor
{
	if (requestor == self.FIA) 
    {
        if(connectServer && self.tcpConnection != nil)
        {
            switch (self.tcpConnection.myState) {
                case CLIENT_INIT: return INIT; break;
                case CLIENT_CONNECTED: return CONNECTED; break;
                case CLIENT_GUIRECVED: return NEW_MODEL; break;
                case CLIENT_IDLE: return SAME_MODEL; break;                    
            }
        }
        else return -1;
    }    
    else return -1;
}

- (void) intConnectionState:(FreeInteractionAreaView *)requestor
{
	if (requestor == self.FIA) 
    {
        //if connectServer and allows to connect, then set connection to init state
        if(connectServer && self.tcpConnection != nil) self.tcpConnection.myState = CLIENT_INIT;
    }    
}

//TODO::Enum Fix:: Assumed that the states are ordered

- (void) incrConnectionState:(FreeInteractionAreaView *)requestor
{
	if (requestor == self.FIA) 
    {
        //if connectServer and allows to connect, increment the state by one
        if(tcpConnection && self.tcpConnection != nil) self.tcpConnection.myState++;
        
        //After every state draw something.
        NSLog(@"DetailVC :: State change draw something" );
        [self.FIA setNeedsDisplay];
    }    
}

#
#
#pragma mark - Managing the detail item
#
#

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//
- (void)setDetailItem:(id)newDetailItem
{
    if (_detailItem != newDetailItem) {
        _detailItem = newDetailItem;
        
        // Update the view.
        [self configureView];
    }

    if (self.masterPopoverController != nil) 
    {
        [self.masterPopoverController dismissPopoverAnimated:YES];
    }        
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//
- (void)configureView
{
    BOOL debugConfigView = YES;    

    if( debugConfigView )
    {
        NSLog(@" ");
        NSLog(@"DetailVC :: configuring view controller .....");   
    }
    [self setTitle:[NSString stringWithString:@"Free Interaction Area"]];

    CGRect bounds = [self.view bounds];
    FIA = [ [FreeInteractionAreaView alloc] initWithFrame:bounds name:@"FIA" withTouch:YES withMultiTouch:YES];
    [FIA setDebugTouch:YES];
    [FIA setBackgroundColor:[UIColor blackColor]];
    self.FIA.FIAdelegate = self;
    
    [self.view addSubview:FIA];
    
    // Update the user interface for the detail item.
    if (self.detailItem) 
    {
        if( debugConfigView ) NSLog(@"DetailVC :: configured view");
//        self.detailDescriptionLabel.text = [self.detailItem description];
    }
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


#
#
#pragma mark - View lifecycle
#
#
//////////////////////////////////////////////////////////////////////////////////////////////////
//
- (void) dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //Determine from defaults in Settings, whether to allow connection to server.
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    BOOL estConnectionToServer = [defaults boolForKey:@"connectToServer"];
    connectServer = estConnectionToServer;
    
    if (connectServer) [self setupConnectionToServer];
    else self.tcpConnection = nil;
    
    [self configureView];
    
    [self setupGestureSupportFIA];
    
    //setup notification for when a GUI spec recieved
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setupRedrawFIA:) name:@"DetailVCRedrawFIA" object:nil];
    
    NSLog(@"Detail View Controller Loaded ..... ");

}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//
- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//
- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//
- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = NSLocalizedString(@"Detail", @"Detail");
    }
    return self;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////////////
// Drawing code.
- (void)drawRect:(CGRect)rect 
{  
    NSLog(@"\tDetailVC :: drawing");
    [self.FIA setNeedsDisplay];
}
 
#
#
#pragma mark - TCP Connection stuff
#
#
//////////////////////////////////////////////////////////////////////////////////////////////////////
// 
//
-(void) setupConnectionToServer
{
    TCPClientOmega *newConnect = [ [TCPClientOmega alloc] initWithFrame:[[UIScreen mainScreen] bounds ]];
    self.tcpConnection = newConnect;  
    [self.tcpConnection estConnectionToServer];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"FIAConnected" object:nil];
}

#
#
#pragma mark - Split view
#
#

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//
- (void)splitViewController:(UISplitViewController *)splitController willHideViewController:(UIViewController *)viewController withBarButtonItem:(UIBarButtonItem *)barButtonItem forPopoverController:(UIPopoverController *)popoverController
{
    barButtonItem.title = NSLocalizedString(@"Master", @"Master");
    [self.navigationItem setLeftBarButtonItem:barButtonItem animated:YES];
    self.masterPopoverController = popoverController;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//
- (void)splitViewController:(UISplitViewController *)splitController willShowViewController:(UIViewController *)viewController invalidatingBarButtonItem:(UIBarButtonItem *)barButtonItem
{
    // Called when the view is shown again in the split view, invalidating the button and popover controller.
    [self.navigationItem setLeftBarButtonItem:nil animated:YES];
    self.masterPopoverController = nil;
}


//////////////////////////////////////////////////////////////////////////////////////////////////////
//- (void) setupGestureSupportFIA
//
- (void)setupGestureSupportFIA
{
    /*
     Create and configure the five recognizers. Add each to the view as a gesture recognizer.
     */
	UIGestureRecognizer *recognizer;
    
    /*
     Create a pinch recognizer and add it to the view.
     Keep a reference to the recognizer to test in gestureRecognizer:shouldReceiveTouch:.
     */
    recognizer = [ [UIPinchGestureRecognizer alloc ] initWithTarget:self.FIA action:@selector(handlePinch:) ];
    [self.FIA addGestureRecognizer:recognizer];
    
    /*
     Create a rotation gesture recognizer.
     We're only interested in receiving messages from this recognizer, and the view will take ownership of it, so we don't need to keep a reference to it.
     */
	recognizer = [[UIRotationGestureRecognizer alloc] initWithTarget:self.FIA  action:@selector(handleRotation:)];
	[self.FIA addGestureRecognizer:recognizer];
    
    /*
     Create a pan gesture recognizer.
     We're only interested in receiving messages from this recognizer, and the view will take ownership of it, so we don't need to keep a reference to it.
     */
    //	recognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self.FIA action:@selector(handlePan:)];
    //    [ (UIPanGestureRecognizer*) recognizer setMinimumNumberOfTouches:3];
    //    [ (UIPanGestureRecognizer*) recognizer setMaximumNumberOfTouches:3];
    //	[self.FIA addGestureRecognizer:recognizer];
    
    // -----------------------------
    // One finger, two taps
    // -----------------------------
    recognizer = [ [UITapGestureRecognizer alloc ] initWithTarget:self.FIA action:@selector(oneFingerTwoTaps:) ];
    [(UITapGestureRecognizer*) recognizer setNumberOfTapsRequired:2];
    [(UITapGestureRecognizer*) recognizer setNumberOfTouchesRequired:1];
    [self.FIA addGestureRecognizer:recognizer];
    
	// -----------------------------
	// Swipe down
	// -----------------------------
    //    recognizer = [ [UISwipeGestureRecognizer alloc] initWithTarget:self.FIA action:@selector(swipeDown:)];
    //    [(UISwipeGestureRecognizer*) recognizer setDirection:UISwipeGestureRecognizerDirectionDown];
    //    [(UISwipeGestureRecognizer*) recognizer setNumberOfTouchesRequired:3];
    //    [self.FIA addGestureRecognizer:recognizer];
    
    // -----------------------------
    // Swipe up
	// -----------------------------
    recognizer = [ [UISwipeGestureRecognizer alloc] initWithTarget:self.FIA action:@selector(swipeUp:)];
    [(UISwipeGestureRecognizer*) recognizer setDirection:UISwipeGestureRecognizerDirectionUp];
    [(UISwipeGestureRecognizer*) recognizer setNumberOfTouchesRequired:1];
    [self.FIA addGestureRecognizer:recognizer];
    
	// -----------------------------
	// Swipe left
	// -----------------------------
    //    recognizer = [ [UISwipeGestureRecognizer alloc] initWithTarget:self.FIA action:@selector(swipeLeft:)];
    //    [(UISwipeGestureRecognizer*) recognizer setDirection:UISwipeGestureRecognizerDirectionLeft];
    //    [(UISwipeGestureRecognizer*) recognizer setNumberOfTouchesRequired:3];
    //    [self.FIA addGestureRecognizer:recognizer];
    
    // -----------------------------
	// Swipe right
	// -----------------------------
    //    recognizer = [ [UISwipeGestureRecognizer alloc] initWithTarget:self.FIA action:@selector(swipeRight:)];
    //    [(UISwipeGestureRecognizer*) recognizer setDirection:UISwipeGestureRecognizerDirectionRight];
    //    [(UISwipeGestureRecognizer*) recognizer setNumberOfTouchesRequired:1];
    //    [self.FIA addGestureRecognizer:recognizer];
    
}
@end
